package com.cq.oa.service.sm.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oa.base.service.impl.BaseServiceImpl;
import oa.base.session.SessionManger;
import oa.base.util.Constants;
import oa.base.util.MD5Ecnrypt;
import oa.base.util.Page;
import oa.base.util.tree.TreeNode;

import com.cq.oa.dao.sm.OrgDao;
import com.cq.oa.dao.sm.UserDao;
import com.cq.oa.dao.sm.UserOrgDao;
import com.cq.oa.domain.sm.Org;
import com.cq.oa.domain.sm.User;
import com.cq.oa.domain.sm.UserOrg;
import com.cq.oa.jdbc.JdbcDao;
import com.cq.oa.service.sm.UserService;
import com.cq.oa.session.SessionUtils;
import com.cq.oa.utils.ChinaUtils;
import com.cq.oa.utils.NullUtil;
import com.cq.oa.utils.StringliptUtil;
import com.cq.oa.utils.TreeNodeUtils;

public class UserServiceImpl extends BaseServiceImpl<User> implements UserService{

	private UserDao userDao;
	private OrgDao orgDao;
	private JdbcDao jdbcDao;
	private UserOrgDao userOrgDao;
	
	
	
	
	@SuppressWarnings("unchecked")
	public Page<User> findByPageParm(Map<String,Object> params,int pageNo,int pageSize){
		Page<User> users=null;
		String deptId = String.valueOf(params.get("deptId"));
		if(!"null".equals(deptId)){
			String otherWhere = "";
			StringBuffer sql = new StringBuffer("select * from sm_user ");
			params.remove("deptId");
			otherWhere = " sid in (select user_sid from sm_user_org where dept_sid="+deptId+")";
			String where = userDao.toSqlString(params);
			if(where.startsWith("where")){
				sql.append(where).append(" and "+otherWhere);
			}else{
				sql.append(" where "+otherWhere);
			}
			users = userDao.pagedSql(sql.toString(), pageNo, pageSize,null);
		}else{
			users = userDao.pagedQuery(params, new HashMap<String,Object>(),new HashMap<String,Object>(), pageNo, pageSize);
		}
		return users;
	}
	
	
	public void setUserOrgDao(UserOrgDao userOrgDao) {
		this.userOrgDao = userOrgDao;
	}
	public void setOrgDao(OrgDao orgDao) {
		this.orgDao = orgDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	public void setJdbcDao(JdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}
	
	public JdbcDao getJdbcDao() {
		return jdbcDao;
	}
	public List<User> findUserList(Map<String, Object> params) {
		return userDao.find(params);
	}
	public User findUser(Map<String, Object> params) {
	    List<User> user = this.findUserList(params);
		return user.size()>0?user.get(0):null;
	}
	public User getUser(Long sid) {
		return userDao.get(sid);
	}
	@SuppressWarnings("unchecked")
	public Page<User> findUserPage(Map<String, Object> filterMap,Map<String, Object> likeMap, Map<String, Object> sortMap,
			int pageNo, int pageSize) {
		return userDao.pagedQuery(filterMap, likeMap, sortMap, pageNo, pageSize);
	}
	public void doCheckAccount(String username, String password,String keyword) throws Exception {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("username", username);
		List<User> users = this.findUserList(params);
		if(users.size()<1){
			throw new Exception("用户名不存在");
		}else{
			User user = users.get(0);
			if(!user.getPassword().equals(MD5Ecnrypt.EncodeMD5Hex(password))){
				throw new Exception("用户名和密码不匹配");
			}
			//设置登录时间
			user.setLastLogin(new Date());
			UserOrg userOrg = this.findUserDept(user.getSid());
			if(NullUtil.isNull(userOrg)){
				throw new Exception("空闲的帐号,无法获知属于哪个部门请维护!");
			}
			//注册session
			SessionUtils.initSession(user, this.findByOrg(user.getOrgSid()), this.findByOrg(userOrg.getDeptSid()));
			this.updateSelect(user);
		}
		
	}
	
	
	/**
	 * 查询单位数据
	 * @param orgId
	 * @return
	 */
	private Org findByOrg(Long orgId){
		Org org = orgDao.get(orgId);
		return org;
	}
	
	/**
	 *  获取人员和部门关系
	 * @param userId
	 * @return
	 * lilang 
	 * 2013-9-12下午3:14:27
	 */
	private UserOrg findUserDept(Long userId){
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("userSid", userId);
		List<UserOrg> userOrgs=userOrgDao.find(params);
		if(userOrgs.size()>0){
			return userOrgs.get(0);
		}else{
			return null;
		}
	}
	
	
	public Long saveUser(User user,Long deptId,String deptCname) throws Exception {
		//转换汉字为拼音
		user.setEname(ChinaUtils.china2pingyin(user.getCname()));
		if(user.getSid()==null){
			//默认 6个0
			user.setPassword("000000");
			if(isHaveAccount(user)){
				userDao.create(user);
				this.createUserOrg(user, deptId, deptCname);
			}else{
				throw new Exception("帐号名称重复:"+user.getUsername());
			}
		}else {
			userDao.update(user);
		}
		System.out.println("添加帐号成功"+user.getUsername());
		return user.getSid();
	}
	
	
	
	
	/**
	 *  是否有这个帐号
	 * @param username
	 * @param orgId
	 * @return
	 * @throws Exception 
	 */
	private boolean isHaveAccount(User user) throws Exception{
		if(user.getOrgSid()==null){
			user.setOrgSid(SessionManger.getOrgId());
		}
		if(user.getPassword()!=null){
			String pass = MD5Ecnrypt.EncodeMD5Hex(user.getPassword());
			user.setPassword(pass);
		}
		String names = "username,orgSid";
		return userDao.isUnique(user, names);
	}
	
	
	private void createUserOrg(User user,Long deptId,String deptCname){
		UserOrg org = new UserOrg();
		org.setDeptSid(deptId);
		org.setDeptCname(deptCname);
		org.setUserSid(user.getSid());
		org.setUserCname(user.getCname());
		this.userOrgDao.create(org);
	}


	/* (non-Javadoc)
	 * @see com.cq.oa.service.sm.UserService#findUserByEmail(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public List<User> findUserByEmail(List<String> emails) {
		String email = StringliptUtil.listToString(emails);
		Map<String,String> params = new HashMap<String, String>();
		params.put(":email", email);
		String sql = "select * from sm_user where EMAIL in (:email) OR sid in (select USER_SID from sm_user_org where  dept_sid in (select sid from sm_org where EMAIL in (:email)))";
		return this.userDao.findSql(sql, params, User.class);
	}
	
	public List<Map<String,Object>> findUserByEmail(String likes,int topNo) {
		Map<String,String> params = new HashMap<String, String>();
		params.put(":email", likes);
		String sql = "SELECT email,cname FROM sm_user WHERE (EMAIL LIKE '%:email%' OR cname LIKE '%:email%') union all select email,cname  from sm_org o where (EMAIL LIKE '%:email%' OR o.cname LIKE '%:email%') limit 0,"+topNo;
		return this.userDao.findBySqlMap(sql, params);
	}


	
	@SuppressWarnings("unchecked")
	public List<User> findUserByDeptId(String deptId){
		Map<String,String> params = new HashMap<String, String>();
		params.put(":deptId", deptId);
		String sql = "select * from sm_user where  sid in (select USER_SID from sm_user_org where  dept_sid =:deptId)   order by order_by asc";
		return this.userDao.findSql(sql, params, User.class);
	}
	
	

	/* (non-Javadoc)
	 * @see com.cq.oa.service.sm.UserService#findOrgChild(java.lang.String)
	 */
	public List<TreeNode> findOrgChild(String id) {
		if(NullUtil.isEmpty(id)){
			id="0";
		}
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		Map<String,Object> params = new HashMap<String, Object>();
		Map<String,Object> like = new HashMap<String, Object>();
		Map<String,Object> sort = new HashMap<String, Object>();
		params.put("orgSid", SessionManger.getOrgId());
		params.put("upId", Long.valueOf(id));
		sort.put(Constants.ORDER_BY_ASC, "orderBy");
		List<Org> orgs=this.orgDao.find(params, like, sort);
		treeNodes.addAll(TreeNodeUtils.bulid2TreeNode(orgs));
		treeNodes.addAll(TreeNodeUtils.bulidUser2TreeNode(this.findUserByDeptId(id)));
		return treeNodes;
	}


	/* (non-Javadoc)
	 * @see com.cq.oa.service.sm.UserService#findUserByName(java.lang.String, int)
	 */
	@SuppressWarnings("unchecked")
	public List<User> findUserByName(String likes, int topNo) {
		Map<String,Object> params = new HashMap<String, Object>();
		Map<String,Object> flter = new HashMap<String, Object>();
		flter.put(Constants.WHERE_LIKE+"cname", likes);
		flter.put(Constants.WHERE_LIKE+"ename", likes);
		params.put(Constants.ORG_SID, SessionManger.getOrgId());
		params.put(Constants.WHERE_OR, flter);
		Map<String,Object> lc = new HashMap<String, Object>();
		Map<String,Object> sc = new HashMap<String, Object>();
		Page<User> page = this.userDao.pagedQuery(params, lc,sc, 1, topNo);
		return page.getRows();
	}
	
	
	
	
}
